<!-- 工作统计页面 -->
<template>
  <view class="workload-container">
    <!-- 时间范围选择 -->
    <view class="filter-section">
      <uni-datetime-picker
        v-model="dateRange"
        type="daterange"
        @change="handleDateRangeChange"
      />
    </view>

    <!-- 统计卡片 -->
    <view class="stats-cards">
      <uni-card title="会话统计">
        <view class="stat-item">
          <text>总会话数</text>
          <text class="stat-value">{{ stats.totalSessions }}</text>
        </view>
        <view class="stat-item">
          <text>平均会话时长</text>
          <text class="stat-value">{{ formatDuration(stats.averageSessionDuration) }}</text>
        </view>
        <view class="stat-item">
          <text>转接次数</text>
          <text class="stat-value">{{ stats.transferCount }}</text>
        </view>
      </uni-card>

      <uni-card title="响应统计">
        <view class="stat-item">
          <text>平均首次响应时间</text>
          <text class="stat-value">{{ formatDuration(stats.averageResponseTime) }}</text>
        </view>
        <view class="stat-item">
          <text>消息总数</text>
          <text class="stat-value">{{ stats.messageCount }}</text>
        </view>
      </uni-card>

      <uni-card title="满意度统计">
        <view class="stat-item">
          <text>评价总数</text>
          <text class="stat-value">{{ satisfactionStats.totalRatings }}</text>
        </view>
        <view class="stat-item">
          <text>平均满意度</text>
          <text class="stat-value">{{ formatScore(satisfactionStats.averageScore) }}</text>
        </view>
      </uni-card>
    </view>

    <!-- 排名列表 -->
    <view class="ranking-section">
      <uni-card title="客服排名">
        <uni-table>
          <uni-tr>
            <uni-th>排名</uni-th>
            <uni-th>客服</uni-th>
            <uni-th>会话数</uni-th>
            <uni-th>平均响应时间</uni-th>
            <uni-th>满意度</uni-th>
          </uni-tr>
          <uni-tr v-for="(item, index) in rankingList" :key="index">
            <uni-td>{{ index + 1 }}</uni-td>
            <uni-td>{{ item.serviceName }}</uni-td>
            <uni-td>{{ item.totalSessions }}</uni-td>
            <uni-td>{{ formatDuration(item.avgResponseTime) }}</uni-td>
            <uni-td>{{ formatScore(item.satisfactionScore) }}</uni-td>
          </uni-tr>
        </uni-table>
      </uni-card>
    </view>
  </view>
</template>

<script>
import { ref, onMounted } from 'vue';
import { getServiceWorkloadStats, getSessionSatisfactionStats, getServiceRanking } from '@/api/stats';

export default {
  name: 'WorkloadStats',
  setup() {
    const dateRange = ref([]);
    const stats = ref({});
    const satisfactionStats = ref({});
    const rankingList = ref([]);

    // 格式化时长
    const formatDuration = (seconds) => {
      if (!seconds) return '0秒';
      if (seconds < 60) return seconds + '秒';
      const minutes = Math.floor(seconds / 60);
      if (minutes < 60) return minutes + '分钟';
      const hours = Math.floor(minutes / 60);
      const remainingMinutes = minutes % 60;
      return hours + '小时' + (remainingMinutes > 0 ? remainingMinutes + '分钟' : '');
    };

    // 格式化评分
    const formatScore = (score) => {
      return score ? score.toFixed(1) : '0.0';
    };

    // 加载统计数据
    const loadStats = async () => {
      if (!dateRange.value || dateRange.value.length !== 2) return;
      
      try {
        // 加载工作量统计
        const workloadRes = await getServiceWorkloadStats({
          startDate: dateRange.value[0],
          endDate: dateRange.value[1]
        });
        stats.value = workloadRes.data;

        // 加载满意度统计
        const satisfactionRes = await getSessionSatisfactionStats({
          startDate: dateRange.value[0],
          endDate: dateRange.value[1]
        });
        satisfactionStats.value = satisfactionRes.data;

        // 加载排名数据
        const rankingRes = await getServiceRanking({
          startDate: dateRange.value[0],
          endDate: dateRange.value[1],
          metric: 'total_sessions'
        });
        rankingList.value = rankingRes.data;
      } catch (error) {
        console.error('加载统计数据失败:', error);
        uni.showToast({
          title: '加载统计数据失败',
          icon: 'none'
        });
      }
    };

    // 处理日期范围变化
    const handleDateRangeChange = (range) => {
      dateRange.value = range;
      loadStats();
    };

    // 组件挂载时设置默认时间范围为最近7天
    onMounted(() => {
      const end = new Date();
      const start = new Date();
      start.setDate(start.getDate() - 6);
      dateRange.value = [
        start.toISOString().split('T')[0],
        end.toISOString().split('T')[0]
      ];
      loadStats();
    });

    return {
      dateRange,
      stats,
      satisfactionStats,
      rankingList,
      formatDuration,
      formatScore,
      handleDateRangeChange
    };
  }
};
</script>

<style lang="scss">
.workload-container {
  padding: 20rpx;

  .filter-section {
    margin-bottom: 20rpx;
  }

  .stats-cards {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300rpx, 1fr));
    gap: 20rpx;
    margin-bottom: 20rpx;

    .stat-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 10rpx 0;

      .stat-value {
        font-weight: bold;
        color: #2979ff;
      }
    }
  }

  .ranking-section {
    margin-top: 20rpx;
  }
}
</style> 